//手动报到-查询患者信息接口 http://1z823403u5.iask.in:8090/pages/viewpage.action?pageId=4555010
var queryPatBdInfoUrl = STSUrl + "/sign/initSign";
//刷卡报到
var queryPatientKeyUrlUrl = STSUrl + "/sign/initSignCardKey";
//根据系统ID，查询队列列表--    http://yahua.tpddns.cn:8090/pages/viewpage.action?pageId=5013604
var queryQueueListBySysUrl = PDJH + "/QcQueue/getNoPageQueueBySysId";
//根据队列ID查询队列下关联医生列表 http://yahua.tpddns.cn:8090/pages/viewpage.action?pageId=4325601
var queryDoctorListByQueueUrl = PDJH + "/QcQueue/getQueueInfoByQueueId";
//初诊报到 --http://1z823403u5.iask.in:8090/pages/viewpage.action?pageId=4555017
var fstBdUrl = STSUrl + "/sign/firstSign";
//复诊报到 --http://1z823403u5.iask.in:8090/pages/viewpage.action?pageId=4555025
var secondBdUrl = STSUrl + "/sign/repeatSign";

//手动分诊 http://1z823403u5.iask.in:8090/pages/viewpage.action?pageId=4555027
var manualTriageUrl = STSUrl + "/sign/manualTriage";
//复诊时默认医生/可选医生
var getDoctorByQueueIdUrl = QueueCallUrl + "/QcQueue/getNotPageDoctorByQueueId";
//判断医生是否在线
var _doctorStatusUrl = CallNumberUrl + "/CallDevice/getDoctorLoginStatus";

var ajaxPrintTicket = STSUrl + "/sign/printOutTicketRepeat";

var ajaxSignUrl = STSUrl+'/sign/bathSign';

//分诊台ID
var _triageId = getDeviceId();

//医院ID
var _hospiId = getHospitalId();

//登录用户ID(护士)
var userId = getLoginUserId();
var ticketInfo = {"status":0,"desc":"操作成功","data":{"rowspacing":"15","content":[{"cKey":"号票标题","eKey":"title","value":"报到凭证","isUsed":"true","editAttr":"{\"isweight\":1,\"font\":\"2\",\"isShow\":0}"},{"cKey":"二维码","eKey":"qRcode","value":"1230601","isUsed":"true","editAttr":"{\"isweight\":\"0\",\"font\":\"10\",\"isShow\":\"0\"}"},{"cKey":"姓名","eKey":"patientName","sort":"1","value":"李焕哲1","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"就诊序号","eKey":"trgSerial","sort":"2","value":"1","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"科室","eKey":"deptName","sort":"3","value":"A门诊","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"号别","eKey":"registerObj","sort":"4","value":"专家队列","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"午别","eKey":"timeType","sort":"5","value":"全天","isUsed":"false","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"诊室","eKey":"deptDiagName","sort":"6","value":"","isUsed":"false","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"医生","eKey":"doctorName","sort":"7","value":"黄子龙","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"挂号时间","eKey":"registerTime","sort":"8","value":"2022-08-26 09:56:09","isUsed":"false","editAttr":"{\"isweight\":0,\"font\":\"1\",\"isShow\":0}"},{"cKey":"报到时间","eKey":"signTime","sort":"9","value":"2022-08-26 10:29:44","isUsed":"true","editAttr":"{\"isweight\":1,\"font\":\"1\",\"isShow\":0}"},{"cKey":"等待人数","eKey":"waitingNum","sort":"10","value":"0","isUsed":"true","editAttr":"{\"isweight\":1,\"font\":\"1\",\"isShow\":0}"},{"cKey":"温馨提示","value2":"请1李焕哲1到就诊","eKey":"reminder","value":"[{\"order\":1,\"type\":\"text\",\"content\":\"请\"},{\"order\":2,\"type\":\"trgSerial\",\"content\":\"就诊序号\"},{\"order\":3,\"type\":\"patientName\",\"content\":\"姓名\"},{\"order\":4,\"type\":\"text\",\"content\":\"到\"},{\"order\":5,\"type\":\"deptDiagName\",\"content\":\"诊室\"},{\"order\":6,\"type\":\"text\",\"content\":\"就诊\"}]","isUsed":"true","editAttr":"{\"isweight\":1,\"font\":\"1\",\"isShow\":0}","order":"[{\"order\":1,\"type\":\"patientName\",\"content\":\"姓名\"},{\"order\":2,\"type\":\"trgSerial\",\"content\":\"就诊序号\"},{\"order\":3,\"type\":\"deptName\",\"content\":\"科室\"},{\"order\":4,\"type\":\"registerObj\",\"content\":\"号别\"},{\"order\":5,\"type\":\"timeType\",\"content\":\"午别\"},{\"order\":6,\"type\":\"deptDiagName\",\"content\":\"诊室\"},{\"order\":6,\"type\":\"doctorId\",\"content\":\"医生\"},{\"order\":6,\"type\":\"registerTime\",\"content\":\"挂号时间\"},{\"order\":6,\"type\":\"signTime\",\"content\":\"报到时间\"},{\"order\":6,\"type\":\"waitingNum\",\"content\":\"等待人数\"}]"}]}};
ticketInfo = {"status":0,"desc":"操作成功","data":{"rowspacing":"15","content":[{"cKey":"号票标题","eKey":"title","value":"报到凭证1","isUsed":"true","editAttr":"{\"isweight\":1,\"font\":\"2\",\"isShow\":0}"},{"cKey":"二维码","eKey":"qRcode","value":"2022090202","isUsed":"true","editAttr":"{\"isweight\":\"0\",\"font\":\"1\"}"},{"cKey":"姓名","eKey":"patientName","sort":"1","value":"李焕哲2","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"就诊序号","eKey":"trgSerial","sort":"2","value":"2","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"科室","eKey":"deptName","sort":"3","value":"A门诊","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"号别","eKey":"registerObj","sort":"4","value":"普通队列1","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"午别","eKey":"timeType","sort":"5","value":"全天","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"诊室","eKey":"deptDiagName","sort":"6","value":"","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"医生","eKey":"doctorName","sort":"7","value":"","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"挂号时间","eKey":"registerTime","sort":"8","value":"2022-09-02 10:38:28","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"报到时间","eKey":"signTime","sort":"9","value":"2022-09-02 10:41:50","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"等待人数","eKey":"waitingNum","sort":"10","value":"1","isUsed":"true","editAttr":"{\"isweight\":0,\"font\":\"0\",\"isShow\":0}"},{"cKey":"温馨提示","value2":"请2李焕哲2到就诊","eKey":"reminder","value":"[{\"order\":1,\"type\":\"text\",\"content\":\"请\"},{\"order\":2,\"type\":\"trgSerial\",\"content\":\"就诊序号\"},{\"order\":3,\"type\":\"patientName\",\"content\":\"姓名\"},{\"order\":4,\"type\":\"text\",\"content\":\"到\"},{\"order\":5,\"type\":\"deptDiagName\",\"content\":\"诊室\"},{\"order\":6,\"type\":\"text\",\"content\":\"就诊\"}]","isUsed":"true","editAttr":"{\"isweight\":1,\"font\":\"1\",\"isShow\":0}","order":"[{\"order\":1,\"type\":\"patientName\",\"content\":\"姓名\"},{\"order\":2,\"type\":\"trgSerial\",\"content\":\"就诊序号\"},{\"order\":3,\"type\":\"deptName\",\"content\":\"科室\"},{\"order\":4,\"type\":\"registerObj\",\"content\":\"号别\"},{\"order\":5,\"type\":\"timeType\",\"content\":\"午别\"},{\"order\":6,\"type\":\"deptDiagName\",\"content\":\"诊室\"},{\"order\":6,\"type\":\"doctorId\",\"content\":\"医生\"},{\"order\":6,\"type\":\"registerTime\",\"content\":\"挂号时间\"},{\"order\":6,\"type\":\"signTime\",\"content\":\"报到时间\"},{\"order\":6,\"type\":\"waitingNum\",\"content\":\"等待人数\"}]"}]}};
//存储队列集合
var qListJsonStr = "";
var patientKeyFz = "";
var pattype = "";
var btnType = "";
var isPretest = "";//预检选项是否开启  1 开启 0 关闭
var _from = "";
$(function () {
    $(document).keypress(function (e) {
        if (e.which == 13) {
            queryPatInfoByInput();
        }
    });
    $('#text_patName').focus().blur(function () {
        $(this).focus();
    });

    // 延迟2S后自动获取焦点
    // 解决老旧机器，C端打印小票弹窗慢，导致无法获取焦点问题
    var t = setTimeout(function () {
        if(!$("#text_patName").is(":focus")){
            $('#text_patName').focus();
        }
        clearTimeout(t);
        t = null;
    },8000);
    var patientKey = GetQueryString('patientKey');
    if(patientKey&&patientKey.trim()!=='') ReadCardInfos(patientKey);
    _from = GetQueryString('from');
});

function readCard() {
    try{
        my_cefsharp.Set_ReadCard_Mode("0");
        my_cefsharp.Get_Card_UID_Cef(ReadCardInfos);
    }catch (e) {
        ReadCardInfos();
    }
}
function ReadCardInfos(_patientKey) {
    _patientKey = _patientKey ||'';
    if(_patientKey=='00000000')  _patientKey = '';
    $('#text_patName').val(_patientKey);
    if(_patientKey!=''){
        queryPatInfoByInput(_patientKey);
    }
}

//1，手动报到-查询患者信息
function queryPatInfoByInput(cadKey) {
    cadKey = cadKey ||'';
    var _patientKey = $("#text_patName").val();
    queryPatInfo(queryPatBdInfoUrl, cadKey, _patientKey);
}

// 获取午别的中文名称
// //午别  0,全天    1,上午       2,下午
function getWubieName(_wuBie) {
    var _wuBieName = '';
    if (_wuBie == '0') {
        _wuBieName = '全天';
    } else if (_wuBie == '1') {
        _wuBieName = '上午';
    } else if (_wuBie == '2') {
        _wuBieName = '下午';
    }

    return _wuBieName;
}

//1，查询患者信息
function queryPatInfo(queryBdInfoUrl, patientKey, _patientKey) {
    if(!_patientKey||_patientKey=='') return layer.msg('请输入患者id!');
    var msgIndex = null;
    $.ajax({
        url: queryBdInfoUrl,
        type: 'post',
        data: {
            triageId: _triageId, //患者就诊号
            patientKey: _patientKey, //患者就诊卡号
            patientCardKey: patientKey//物理卡号
        },
        success: function (d) {
            var dataInfo = JSON.parse(d);
            layer.close(msgIndex);
            if (dataInfo.status == "0") {//报到
                // 查询就诊号-浮层 隐藏
                $("#d_query").hide();
                // 报到-浮层 隐藏
                $("#d_bd").hide();
                // 选择号别-浮层 显示
                $("#d_display").show();
                // 打印层 隐藏
                $("#print").hide();

                dealQueueList(dataInfo.data)
            }
                //错误信息
            else {
                layer.alert(dataInfo.desc, { icon: 2 });
            }
        }, error: function () {
        }
    });
}
// var res  ={"status":0,"desc":"成功返回报到队列列表","data":{"signData":[{"pretestStage":"0","relationType":"1","queueId":"0d841fe1c8a94400b275d32b1394756c","patientName":"口腔A1","deptName":"口腔科","systemId":"bb024f348ed545d4b35584ef3effe394","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:35","bookSignInStatus":"1","isTriage":"0","deptId":"0b84c6d11a8240a4804f877979be2382","registerObjName":"A普通队列","isSign":"0","doctorName":"","queueName":"A普通队列","systemName":"口腔科分诊叫号子系统","registerObjKey":"0b84c6d11a8240a4804f877979be2382_12","patientKey":"1008613","id":"ee3450fea94b46d8b3fb51d98f135791"},{"pretestStage":"0","relationType":"1","queueId":"2fd0f0be4d2c49569f00e79de0a098c7","patientName":"口腔B1","deptName":"口腔科","systemId":"bb024f348ed545d4b35584ef3effe394","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:38","bookSignInStatus":"1","isTriage":"0","deptId":"0b84c6d11a8240a4804f877979be2382","registerObjName":"普通队列","isSign":"0","doctorName":"","queueName":"普通队列","systemName":"口腔科分诊叫号子系统","registerObjKey":"0b84c6d11a8240a4804f877979be2382_1","patientKey":"1008613","id":"1b671364a7f446418ca5a50e5b02600f"},{"pretestStage":"0","relationType":"2","queueId":"dbc246d3d3574c88a785909e2ecc0679","patientName":"张胖子4","deptName":"消化内科","systemId":"c4fec61de9214603988fe61395d82f13","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:40","bookSignInStatus":"1","isTriage":"0","deptId":"2f07913d6469440283a01391255570a2","registerObjName":"消化肝病专病门诊","isSign":"0","doctorName":"张杰","queueName":"消化肝病专病门诊","systemName":"消化内科分诊叫号子系统","registerObjKey":"161ace177f9d46ce8ffe90df87032e8e_6","patientKey":"1008613","id":"d75812ddddeb4aff8319accf486c98d3"},{"pretestStage":"0","relationType":"1","queueId":"e1c837f6ae07410c884230b816512079","patientName":"赵山河5","deptName":"消化内科","systemId":"c4fec61de9214603988fe61395d82f13","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:43","bookSignInStatus":"1","isTriage":"0","deptId":"2f07913d6469440283a01391255570a2","registerObjName":"消化内科普通队列","isSign":"0","doctorName":"","queueName":"消化内科普通队列","systemName":"消化内科分诊叫号子系统","registerObjKey":"2f07913d6469440283a01391255570a2_1","patientKey":"1008613","id":"de34e5397dfa47479ecba550c62fd7fc"}],"unSignData":[],"resData":[{"deptName":"口腔科","systemId":"bb024f348ed545d4b35584ef3effe394","queueInfo":[{"pretestStage":"0","relationType":"1","queueId":"0d841fe1c8a94400b275d32b1394756c","patientName":"口腔A1","deptName":"口腔科","systemId":"bb024f348ed545d4b35584ef3effe394","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:35","bookSignInStatus":"1","isTriage":"0","deptId":"0b84c6d11a8240a4804f877979be2382","registerObjName":"A普通队列","isSign":"0","doctorName":"","queueName":"A普通队列","systemName":"口腔科分诊叫号子系统","registerObjKey":"0b84c6d11a8240a4804f877979be2382_12","patientKey":"1008613","id":"ee3450fea94b46d8b3fb51d98f135791"},{"pretestStage":"0","relationType":"1","queueId":"2fd0f0be4d2c49569f00e79de0a098c7","patientName":"口腔B1","deptName":"口腔科","systemId":"bb024f348ed545d4b35584ef3effe394","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:38","bookSignInStatus":"1","isTriage":"0","deptId":"0b84c6d11a8240a4804f877979be2382","registerObjName":"普通队列","isSign":"0","doctorName":"","queueName":"普通队列","systemName":"口腔科分诊叫号子系统","registerObjKey":"0b84c6d11a8240a4804f877979be2382_1","patientKey":"1008613","id":"1b671364a7f446418ca5a50e5b02600f"}],"systemName":"口腔科分诊叫号子系统","deptId":"0b84c6d11a8240a4804f877979be2382"},{"deptName":"消化内科","systemId":"c4fec61de9214603988fe61395d82f13","queueInfo":[{"pretestStage":"0","relationType":"2","queueId":"dbc246d3d3574c88a785909e2ecc0679","patientName":"张胖子4","deptName":"消化内科","systemId":"c4fec61de9214603988fe61395d82f13","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:40","bookSignInStatus":"1","isTriage":"0","deptId":"2f07913d6469440283a01391255570a2","registerObjName":"消化肝病专病门诊","isSign":"0","doctorName":"张杰","queueName":"消化肝病专病门诊","systemName":"消化内科分诊叫号子系统","registerObjKey":"161ace177f9d46ce8ffe90df87032e8e_6","patientKey":"1008613","id":"d75812ddddeb4aff8319accf486c98d3"},{"pretestStage":"0","relationType":"1","queueId":"e1c837f6ae07410c884230b816512079","patientName":"赵山河5","deptName":"消化内科","systemId":"c4fec61de9214603988fe61395d82f13","showName":"","wuBie":"0","registerTime":"2024-05-15 13:29:43","bookSignInStatus":"1","isTriage":"0","deptId":"2f07913d6469440283a01391255570a2","registerObjName":"消化内科普通队列","isSign":"0","doctorName":"","queueName":"消化内科普通队列","systemName":"消化内科分诊叫号子系统","registerObjKey":"2f07913d6469440283a01391255570a2_1","patientKey":"1008613","id":"de34e5397dfa47479ecba550c62fd7fc"}],"systemName":"消化内科分诊叫号子系统","deptId":"2f07913d6469440283a01391255570a2"}]}}
function dealQueueList(obj) {
    /**
     * 1、口腔科普通队列要支持选择医生不能进行自动到，需要手动报到，选择医生
     * 2、复诊患者，原医生不在线的也需要手动报到
     * 3、初诊患者未诊结的，无法进行复诊操作
     * 4、初诊/复诊医生在线的患者允许自动报到，不是【口腔科的普通队列】允许自动报到
     * **/
    var signData = obj.signData || []; // 允许自动报到的数据
    var unSignData = obj.unSignData || []; // 不允许自动报到的数据，需要手动报到
    var signIds = [],unSignIds = [],special = [];
    var frag = '',unSignFrag = '',_wuBieName,_isPretest,_docName,_sysName,_displayMsg,_radioVal;
    // todo 是否有报到信息
    if(signData.length<0&&unSignData.length<0){
        layer.closeAll();
        parent.layer.closeAll();
        parent.layer.alert('该患者已报到，请勿重复操作', { icon: 2 });
    }else {
        // 需要判断是否有口腔科普通队列
        for (var i = 0,lens = signData.length; i < lens; i++) {
            if(signData[i]){
                 _wuBieName = getWubieName(signData[i].wuBie);
                 _isPretest = showIsPretest(signData[i].systemId);//系统是否开启预检选项
                 _docName = signData[i].queueName ||'';
                 _sysName =  signData[i].systemName || '';
                 _displayMsg =(signData[i].isSign == 0?'初诊：':'复诊：')+ (signData[i].deptName|| '') + "," + _docName + "," + _wuBieName;
                 _radioVal = signData[i].patientKey + "\2" + signData[i].patientName + "\2" + signData[i].queueId + "\2"
                        + _docName + "\2" + signData[i].wuBie + "\2" + signData[i].systemId + "\2" + signData[i].deptId + "\2" + signData[i].registerObjKey + "\2" + signData[i].id + "\2" + _wuBieName + "\2" + signData[i].deptName + "\2" + signData[i].registerTime + "\2" + signData[i].isSign + "\2" + signData[i].pretestStage + "\2" + _isPretest+ "\2" + _sysName;
                if ( signData[i].isSign == 0) {
                    frag += "<span><label>";
                    frag += '<input value="' + _radioVal + '" '+(signData[i].bookSignInStatus==0?'disabled':'')+' type="radio" id="f' + signData[i].registerObjKey + '" name="radio_queue" />';
                    if(signData[i].bookSignInStatus==0){
                        frag +=  '<i style="color:#999;font-style: normal">'+_displayMsg+'</i></label>';
                        frag += '<span style="color:red;">已过期，请重新挂号</span>';
                    }else {
                        frag +=  _displayMsg;
                    }
                    frag += '</label></span>';
                }else {
                    unSignFrag += "<span><label>";
                    unSignFrag += '<input value="' + _radioVal + '" '+(signData[i].bookSignInStatus==0?'disabled':'')+' type="radio" id="f' + signData[i].registerObjKey + '" name="radio_queue" />';
                    if(signData[i].bookSignInStatus==0){
                        unSignFrag +=  '<i style="color:#999;font-style: normal">'+_displayMsg+'</i></label>';
                        unSignFrag += '<span style="color:red;">已过期，请重新挂号</span>';
                    }else {
                        unSignFrag +=  _displayMsg;
                    }
                    unSignFrag += '</label></span>';
                }
                // todo 如果是口腔科，并且是普通队列需要选择医生，不允许自动报到 需要根据子系统名称判断是否是口腔科室
                if(signData[i].relationType==1&&_sysName.indexOf("口腔科")>-1){
                    // 如果是普通队列，并且是口腔科的话，不允许自动报到
                    // todo 薛少琪反馈，signData 数据全量传，不需要前端筛选到不允许报到队列中
                    special.push({
                        patientKey:signData[i].patientKey,
                        id:signData[i].id
                    });
                }else {
                    signIds.push(signData[i].id);
                }
            }
        }
        // 这是需要手动报到的数据
        for (var j = 0,lengths = unSignData.length; j < lengths; j++) {
            if(unSignData[j]){
                unSignIds.push(unSignData[j].id);
                _wuBieName = getWubieName(unSignData[j].wuBie);
                _isPretest = showIsPretest(unSignData[j].systemId);//系统是否开启预检选项
                _docName = unSignData[j].queueName ||'';
                _sysName =  unSignData[j].systemName || '';
                _displayMsg =(unSignData[j].isSign == 0?'初诊：':'复诊：')+ (unSignData[j].deptName|| '') + "," + _docName + "," + _wuBieName;
                _radioVal = unSignData[j].patientKey + "\2" + unSignData[j].patientName + "\2" + unSignData[j].queueId + "\2"
                        + _docName + "\2" + unSignData[j].wuBie + "\2" + unSignData[j].systemId + "\2" + unSignData[j].deptId + "\2" + unSignData[j].registerObjKey + "\2" + unSignData[j].id + "\2" + _wuBieName + "\2" + unSignData[j].deptName + "\2" + unSignData[j].registerTime + "\2" + unSignData[j].isSign + "\2" + unSignData[j].pretestStage + "\2" + _isPretest+ "\2" + _sysName;
                unSignFrag += "<span><label>";
                unSignFrag += '<input value="' + _radioVal + '" '+(unSignData[j].bookSignInStatus==0?'disabled':'')+' type="radio" id="f' + unSignData[j].registerObjKey + '" name="radio_queue" />';
                if(unSignData[j].bookSignInStatus==0){
                    unSignFrag +=  '<i style="color:#999;font-style: normal">'+_displayMsg+'</i></label>';
                    unSignFrag += '<span style="color:red;">已过期，请重新挂号</span>';
                }else {
                    unSignFrag +=  _displayMsg;
                }
                unSignFrag += '</label></span>';
            }
        }
        $(".s_bdqueuelist").html(frag); // 允许自动报到
        $(".s_returnVisit").html(unSignFrag); // 不允许自动报到，比如初诊医生不在线的，需要手动报到
        if(frag!==''){
            $('.s_bdqueuelist span:first-child input[name="radio_queue"]').prop('checked',true);
        }else {
            $('.s_returnVisit span:first-child input[name="radio_queue"]').prop('checked',true);
        }

        // 有需要自动报到的优先处理，需要自动报到的
        if(signIds.length>0) {
            // 是有允许报到的数据，需要自动报到
            autoSignData(signIds,unSignIds);
        }else {
            // todo 如果是口腔科，并且是普通队列需要选择医生
            // 第二次刷卡才会处理这种的，只有一个自动下一步
            // 现场要求除口腔科外多个号，顺序报到
            if(special.length===1){
                goBd();
            }
            if(lengths===1){
                goBd();
            }
        }

    }

}

/**
 * @description: 自动报到
 * @author: lhf
 * **/
function autoSignData(ids,unSignids) {
    $.ajax({
        url: ajaxSignUrl,
        data: {
            ids: ids.join(','),
            unSignids: unSignids.join(','),
            triageId: _triageId
        },
        type: 'post',
        beforeSend: function () {
            parent.layer.load(2);
        },
        success: function (d) {
            var res = JSON.parse(d);
            if(res.status == "0"){
                var signIds = res.data.newSignIds || []; // 报到成功的需要打印小票
                var unSignReason = res.data.unSignReason || ''; // 报到失败的需要提示
                fetchTicketsWithDelay(signIds,1000,function () {
                    if(unSignReason!==''){
                        layer.alert(unSignReason, { title: '提示',icon: 2,yes:function (index) {
                                layer.close(index);
                                parent.layer.closeAll();
                                autoOpenLayer();
                            }});
                    }else {
                        parent.layer.closeAll();
                        autoOpenLayer();
                    }
                });
            }else {
                layer.alert(res.desc, { title: '提示', icon: 2,btn: ['确定'],yes:function (index) {
                        layer.close(index);
                        parent.layer.closeAll();
                        autoOpenLayer()
                    }});
            }
        }
    });
}
function fetchTicketsWithDelay(signIds, delay,callback) {
    function fetchNext(index) {
        if (index < signIds.length) {
            getTicketInfo(signIds[index]);
            setTimeout(function (){
                fetchNext(index + 1);
            }, delay);
        }else {
            callback&&callback();
        }
    }

    fetchNext(0);
}
function autoOpenLayer() {
    if(!_from || _from!='wbd'){
        //报到成功之后再次报到弹窗
        parent.document.getElementById('d_right_content').getElementsByTagName('iframe')[0].contentWindow.autoXcbd();
    }
}

function closeWin() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

//2，选择队列，并跳转到报到页面
function goBd() {
    //赋值
    var _radio = $("input[name='radio_queue']:checked");

    //console.log($(_radio).prop("id"));
    if ($(_radio).prop("id") == undefined) {
        layer.alert("请选择队列");
        return;
    } else {

        // 查询就诊号-浮层 隐藏
        $("#d_query").hide();
        // 报到浮层-浮层 显示
        $("#d_bd").show();
        // 选择号别-浮层 隐藏
        $("#d_display").hide();
        // 打印层 隐藏
        $("#print").hide();
        //var _radioVal = _patientKey + "\2" + _patientName + "\2" + _queueId + "\2" + _doctorName + "\2" + _wuBie;
        //console.log(_radioVal);
        //选择的号别ID
        var _radioVal = $(_radio).val();
        var _patientKey = _radioVal.split("\2")[0];
        patientKeyFz = _patientKey;
        var _patientName = _radioVal.split("\2")[1];
        var _queueId = _radioVal.split("\2")[2];
        var _doctorName = _radioVal.split("\2")[3];
        var _sysId = _radioVal.split("\2")[5];
        var _deptId = _radioVal.split("\2")[6];
        var _registerObjKey = _radioVal.split("\2")[7];
        var _id = _radioVal.split("\2")[8];
        var _wuBie = _radioVal.split("\2")[9];
        var _deptName = _radioVal.split("\2")[10];
        var _registerTime = _radioVal.split("\2")[11];
        var _isSign = _radioVal.split("\2")[12];
        pattype = _radioVal.split("\2")[12];
        var color_status = _radioVal.split("\2")[13];
        isPretest = _radioVal.split("\2")[14];
        var _sysName = _radioVal.split("\2")[15];

        $("#hid_deptId").val(_deptId);
        $("#hid_id").val(_id);
        $("#hid_queueId").val(_queueId);
        $("#hid_isSign").val(_isSign);
        $("#hid_sysId").val(_sysId);
        $("#hid_registerObjKey").val(_registerObjKey);
        $("#hid_patId").val(_id);
        $("#hid_wuBie").val(_wuBie);
        $("#hid_deptName").val(_deptName);
        $("#hid_registerTime").val(_registerTime);
        $("#hid_patKey").val(_patientKey);
        $("#txt_jznumber").val(_patientKey);
        $("#txt_patName").val(_patientName);
        $("#txt_wb").val(_wuBie);
        // var colorStatus = localStorage["colorStatus"];
        if (isPretest == 1) {//预检选项开启
            $("#color_buttons").show();
            $("#msg-for-txt_pretestStage").show();
        } else {
            btnType = 3;
            $("#color_buttons").hide();
            $("#msg-for-txt_pretestStage").hide();
        }
        if (isPretest == 1) {//预检选项开启
            if (_isSign == 1) {
                //复诊时判断是初诊时是否时红色预检选项
                if (color_status == 1) {
                    var count1 = $(".s_returnVisit span input").length;
                    var count = $(".s_bdqueuelist span input").length;
                    if (count1 == 1 && count == 0) {
                        layer.alert('该患者初诊时为“红色”预检分级,请直接为其安排复诊！', {
                            closeBtn: 0,
                            icon: 2
                        }, function () {
                            closeWin();
                        });
                    } else {
                        $("#d_display").show();
                        $("#d_query").hide();
                        $("#d_bd").hide();
                        $("#print").hide();
                        layer.alert("该患者初诊时为“红色”预检分级,请直接为其安排复诊！", { icon: 2 });
                    }
                    return;
                } else if (color_status == 2) {
                    btnType = 2;
                    $(".btn").removeClass('on');
                    $("#but_yellow").addClass("on");
                    $("#but_red").attr('disabled', "disabled");
                    $("#but_green").attr('disabled', "disabled");
                } else if (color_status == 3) {
                    btnType = 3;
                    $("#but_red").attr('disabled', "disabled");
                    $("#but_yellow").attr('disabled', "disabled");
                    $(".btn").removeClass('on');
                    $("#but_green").addClass("on");
                }
            } else {
                btnType = "";
            }
        }
        var _opHtml = "";
        // 查询系统下的队列列表

        var alertIndex = null;
        $.ajax({
            url: queryQueueListBySysUrl,
            data: {
                deptId: _deptId,
                sysId: _sysId
            },
            type: 'get',
            beforeSend: function () {
                alertIndex = layer.alert('查询中', {
                    icon: 16
                });
            },
            success: function (d) {
                layer.close(alertIndex);

                if (JSON.parse(d).status == '0') {
                    var dataInfo = JSON.parse(d).data;
                    qListJsonStr = dataInfo;
                    for (var i = 0; i < dataInfo.length; i++) {
                        var _mQueueId = dataInfo[i].queueId;
                        var _qQueueName = dataInfo[i].queueName;
                        var deptid = dataInfo[i].deptId;
                        var _relationType = dataInfo[i].relationType;//普通队列：1，专家队列：2
                        var _queueStatus = dataInfo[i].queueStatus;//队列在线状态，0 在线，1暂停接诊 2 离线

                        _opHtml += "<option data-queueStatus='" + _queueStatus + "' data-deptid='" + deptid + "' data-relationType='" + _relationType + "' value='" + _mQueueId + "'>" + _qQueueName + "</option>";
                    }
                    //队列下拉条 赋值
                    $("#select_queue").html(_opHtml);
                    //选中指定队列
                    $("#select_queue").find("option[value='" + _queueId + "']").attr("selected", true);
                    //根据队列显示医生
                    // var relationType = $("#select_queue").find("option:selected").attr("data-relationType");
                    var relationTypenew = $('#select_queue option:selected').attr("data-relationType");
                    // 如果是普通队列，并且是口腔科才执行
                    if (relationTypenew == 1&&_sysName.indexOf("口腔科")>-1){
                        $("#doctorNameFirst").hide();
                        $("#doctorNameSecond").show();
                        var msg = "普通队列请选择医生！";
                        doctorNameInfo(_queueId, relationTypenew, msg, _deptId);
                        return;
                    }

                    var queueStatus = $('#select_queue option:selected').attr("data-queueStatus");
                    if (_isSign == 0) {
                        $("#doctorNameFirst").show();
                        $("#doctorNameSecond").hide();
                        $("#txt_doctorName").val(_doctorName);
                        $("#hid_doctorName").val(_doctorName);
                        // 如果是出诊，医生不在线执行
                        if (queueStatus == 2) {
                            layer.alert("您所选队列已离线，请为其指定其他队列或继续分诊。", {
                                closeBtn: 0,
                                // btn: ['确定', '取消'],
                                icon: 7,
                                zIndex: 19892002
                            }, function (index) {
                                layer.close(layer.index);
                            });
                        }else {
                            //单个号，并且医生在线自动报到
                            // 多个号选择队列之后自动报到
                            bd();
                        }
                    } else if (_isSign == 1) {
                        $("#doctorNameFirst").hide();
                        $("#doctorNameSecond").show();
                        var relationType = $('#select_queue option:selected').attr("data-relationType");
                        if (queueStatus == 2) {
                            layer.alert("您所选队列已离线，请为其指定其他队列或继续分诊。", {
                                closeBtn: 0,
                                // btn: ['确定', '取消'],
                                icon: 7,
                                zIndex: 19892002
                            }, function (index) {
                                layer.close(layer.index);
                                var msg = "该患者初诊医生已不在线！";
                                doctorNameInfo(_queueId, relationType, msg, _deptId);
                            });
                        } else {
                            var msg = "该患者初诊医生已不在线！";
                            doctorNameInfo(_queueId, relationType, msg, _deptId);
                        }
                    }
                }
            }
        });
    }
}

//复诊时查询初诊医生及该队列下的全部医生
function doctorNameInfo(queueId, relationType, msg, deptId) {
    var _doctorHtml = "";
    var countDoctor = 0;
    if (relationType == 1) {
        _doctorHtml = "<option value=''>全部医生</option>";
        countDoctor = 1;
    }

    var alertIndex = null;
    $.ajax({
        url: getDoctorByQueueIdUrl,
        data: {
            deptId: deptId,
            hospitalId: _hospiId,
            queueId: queueId,
            patientKey: patientKeyFz
        },
        type: 'get',
        beforeSend: function () {
            alertIndex = layer.msg('查询中', { icon: 16 });
        },

        success: function (d) {

            layer.close(alertIndex);

            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var lengthList = dataInfo.length;
                countDoctor += lengthList;
                for (var i = 0; i < lengthList; i++) {
                    var _doctorId = dataInfo[i].doctorId;
                    var _doctorName = dataInfo[i].doctorName;
                    var _loginStatus = dataInfo[i].loginStatus;//初诊医生展示字段  0：在线 1：暂停  2：离线
                    var fontColor = "color: #0f0f0f";

                    if (_loginStatus == 2) {
                        layer.msg(msg, { time: 2000, zIndex: 198920000, anim: 5 });
                    }
                    if (_loginStatus == 1 || _loginStatus == 0) {
                        _doctorHtml += "<option style='" + fontColor + "' selected data-status='" + _loginStatus + "' value='" + _doctorId + "'>" + _doctorName + "</option>";
                    }
                    else {
                        _doctorHtml += "<option  data-status='" + _loginStatus + "' value='" + _doctorId + "'>" + _doctorName + "</option>";
                    }
                }
                //判断队列医生人数
                if (countDoctor == 1) {
                    $("#txt_doctorNames").prop("disabled", true);
                    $("#txt_doctorNames").css({ "color": "#B8B7B8" });
                } else {
                    $("#txt_doctorNames").prop("disabled", false);
                }
                //医生下拉条 赋值
                $("#txt_doctorNames").html(_doctorHtml);
                var _docId = $('#txt_doctorNames option:selected').val();
                var _docName = $('#txt_doctorNames option:selected').text();
                $("#hid_doctorName").val(_docName);
                $("#hid_doctor").val(_docId);
                // getDoctorStatus(queueId,_docId)
            } else {
                layer.alert(JSON.parse(d).desc, { icon: 2 });
            }
        }
    });
}
function changeDoctor() {
    var queueId = $('#select_queue option:selected').val();
    var _docId = $('#txt_doctorNames option:selected').val();
    var _loginStatus = $('#txt_doctorNames option:selected').attr("data-status");
    $.ajax({
        url: _doctorStatusUrl,
        type: "get",
        data: {
            hospitalId: _hospiId,
            queueId: queueId,
            doctorId: _docId
        },
        success: function (data) {
            var result = JSON.parse(data);
            var msg = "该医生不在线!";
            if (result.data == 0) { //医生离线
                var doctorName = $('#txt_doctorNames option:selected').text();
                if (doctorName != "全部医生") {
                    if (_loginStatus == 2) {
                        msg = "该患者初诊医生已不在线！";
                    } else {
                        msg = "该医生不在线!";
                    }
                    layer.msg(msg, { time: 2000, zIndex: 198920000, anim: 5 });
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {

            layer.alert("操作失败!", { icon: 2 });
        }
    });
}

// 生成二维码
//function genImgCode(patientId) {
//  $("#imgCode").qrcode({
//      width: 50, //宽度
//      height: 50, //高度
//      text: patientId
//  });
//
//  var canvas = $("#imgCode canvas");
//  //将canvas转换成png图片，才能被打印机识别打印
//  var img = canvas[0].toDataURL("image/png");
//  $("#imgCode").html("<img src='" + img + "'>");
//}

// 生成一维码
function getLineCode(content) {
    var myConfigs = {
        format: "CODE128",
        displayValue: true,
        fontSize: 20,
        height: 30,
        textAlign: "center",
        backgroundColor: "",
        lineColor: "#000"//条形码颜色
    };

    //$("#lineCode").barcode(content, "code128",{barWidth:1, barHeight:30,showHRI:false});
    $('#lineCode').JsBarcode(content, myConfigs);
}

// 报到打印（通过css定义打印格式）
function registerPrintByWindow(id) {
    var _registerId = id;
    var _patientId = $("#hid_patKey").val();
    var _patientName = $('#txt_patName').val();
    var _deptName = $('#hid_deptName').val();
    var _numType = $("#select_queue option:selected").text();
    var _currentTime = getNowFormatDate();

    $("#hospitalName").html(localStorage["hospitalName"]);
    $("#registerId").html(_registerId);
    //  $("#patientId").html(_patientId);
    $("#patientName").html(_patientName);
    $("#deptName").html(_deptName);
    $("#numType").html(_numType.substr(0, _numType.length - 1));
    $("#registerTime").html(_currentTime);
    $("#arrivalTime").html(_currentTime);

    var printData = document.all.item("print").innerHTML;
    var preContent = window.document.body.innerHTML;
    var printContent = printData;
    window.document.body.innerHTML = printContent;
    window.print();
    window.document.body.innerHTML = preContent;
}

// 报到打印（通过LODOP定义打印格式）
function registerPrintByLodop() {
    // 生成二维码
    var _patientKey = $("#hid_patKey").val();
    //  genImgCode(_patientKey);

    // 生成条形码
    getLineCode(_patientKey);

    var _patientId = $("#hid_patKey").val();
    var _patientName = $('#txt_patName').val();
    var _wuBie = $('#hid_wuBie').val();
    var _deptName = $('#hid_deptName').val();
    var _numType = $("#select_queue option:selected").text();
    var _currentTime = getNowFormatDate();
    var _registerId = $('#hid_registerId').val();//就诊序号
    var prePatientNum = $('#hid_prePatientNum').val();//排队人数
    var registerTime = $('#hid_registerTime').val();//挂号时间

    $("#hospitalName").html(localStorage["hospitalName"]);
    $("#registerId").html(_registerId);
    //  $("#patientId").html(_patientId);
    $("#patientName").html(_patientName);
    $("#deptName").html(_deptName);
    //  $("#wuBie").html(_wuBie);
    $("#numType").html(_numType.substr(0, _numType.length));
    $("#registerTime").html(registerTime);
    $("#arrivalTime").html(_currentTime);
    $("#prePatientNum").html(prePatientNum);

    var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
    var printData = document.all.item("print").innerHTML;
    LODOP.SET_PRINT_PAGESIZE(1, "75mm", "135mm", "");
    LODOP.ADD_PRINT_HTM("0mm", "0mm", "70mm", "135mm", printData);
    LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS", true);
    // 打印浏览
    //LODOP.PREVIEW();
    // 打印
    LODOP.PRINT();
}

// 报到打印（通过LODOP定义打印格式）
function registerPrintByCSharp(signtime) {
    var _patientId = $("#hid_patKey").val();
    var _patientName = $('#txt_patName').val();
    var _wuBie = $('#hid_wuBie').val();
    var _deptName = $('#hid_deptName').val();
    var _numType = $("#select_queue option:selected").text();
    //  var _currentTime = getNowFormatDate();
    var _registerId = $('#hid_registerId').val();//就诊序号
    var prePatientNum = $('#hid_prePatientNum').val();//排队人数
    var registerTime = $('#hid_registerTime').val();//挂号时间

    $("#hospitalName").html(localStorage["hospitalName"]);
    $("#registerId").html(_registerId);
    //  $("#patientId").html(_patientId);
    $("#patientName").html(_patientName);
    $("#deptName").html(_deptName);
    //  $("#wuBie").html(_wuBie);
    $("#numType").html(_numType.substr(0, _numType.length));
    $("#registerTime").html(registerTime);
    $("#arrivalTime").html(signtime);
    $("#prePatientNum").html(prePatientNum);

    // 获取printhtml内容
    var printData = document.all.item("print").innerHTML;
    var htmlText = "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta charset=\"utf-8\" /><title></title></head><body>" +
        "<div id=\"print\" style=\"width: 70mm; height:135mm;left:15px;position:absolute\">" + printData + "</div></body></html>";

    // 通知csharp做打印
    PrintByCSharp(_patientId, htmlText);
}

//报到
function bd() {
    var requrl = "";
    //初诊
    if (pattype == 0) {
        requrl = fstBdUrl;
    }
        //复诊
    else if (pattype == 1) {
        requrl = secondBdUrl;
    }
    //未选红黄绿按钮时提示内容
    var colorStatusDefault = "";
    if (isPretest == "") {
        colorStatusDefault = localStorage["colorStatus"];
    } else {
        colorStatusDefault = isPretest;
    }
    if (colorStatusDefault == 1) {
        if (pattype == 0) {
            if (btnType == "") {
                $("#msg-for-txt_pretestStage").html("请选择预检选项！").css({ "color": "red", "font-weight": "bold" });
                return;
            }
        }
    }
    var queueId = $("#select_queue").val();
    var _docId = $('#txt_doctorNames option:selected').val();
    var _docName = $('#txt_doctorNames option:selected').text();
    $.ajax({
        url: requrl,
        type: 'post',
        data: {
            hospitalId: _hospiId,   //医院ID
            triageId: _triageId,   //分诊台ID
            registerObjKey: $("#hid_registerObjKey").val(), //队列key
            registerObjName: _docName,  //医生的名称
            id: $("#hid_patId").val()  //患者ID
        },
        success: function (d) {
            var jsonObj = JSON.parse(d);
            if (jsonObj.status == '0') {
                //初诊报到时 jsonObj.data 为：患者挂号id(就是挂号表里的id)
                //复诊报到时 jsonObj.data 为：患者报到id(就是患者报到表的signId)
                var id = JSON.parse(d).data;

                if (id != null) {
                    //报到成功进行分诊
                    manualTriage(id, queueId);

                }
            } else {
                //报到异常的提示信息
                layer.msg(jsonObj.desc);
            }
        }
    });
}

//点击红色按钮
function btnRed() {
    btnType = 1;
    $(".btn").removeClass('on');
    $("#but_red").addClass('on');
    $("#msg-for-txt_pretestStage").html("");
}

//点击黄色按钮
function btnYellow() {
    btnType = 2;
    $(".btn").removeClass('on');
    $("#but_yellow").addClass('on');
    $("#msg-for-txt_pretestStage").html("");

}

//点击绿色按钮
function btnGreen() {
    btnType = 3;
    $(".btn").removeClass('on');
    $("#but_green").addClass('on');
    $("#msg-for-txt_pretestStage").html("");

}

// 切换队列 重置医生
function changeQueue() {
    var queueId = $("#select_queue").val();
    var deptid=  $("#select_queue option:selected").data('deptid');
    $.ajax({
        url: queryDoctorListByQueueUrl,
        type: 'get',
        data: {
            queueId: queueId
        },
        beforeSend: function () {
            layer.msg('查询中...', { time: 1000 });
        },
        complete: function () {
            // layer.closeAll();
        },
        success: function (d) {
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var relationType = dataInfo.relationType;//队列类型 1:普通队列  2：专家队列
                var queueDoctorInfo = dataInfo.queueDocInfo;
                var queueStatus = dataInfo.queueStatus;//0：在线  1：暂停   2：离线
                if (pattype == 0) {
                    if (relationType == 1) {
                        $("#txt_doctorName").val("全部医生");
                    } else if (relationType == 2) {
                        var _queueInfo = queueDoctorInfo[0];
                        var _docName = _queueInfo.docName;
                        $("#txt_doctorName").val(_docName);
                        $("#hid_doctorName").val(_docName);
                    }
                    if (queueStatus == 2) {
                        layer.alert("您所选队列已离线，请为其指定其他队列或继续分诊。", {
                            closeBtn: 0,
                            // btn: ['确定'],
                            icon: 7,
                            zIndex: 19892002,
                            cancel: function () {
                            },
                            yes: function (index) {
                                layer.close(layer.index);
                            }
                        })
                    }
                } else if (pattype == 1) {
                    $("#doctorNameFirst").hide();
                    $("#doctorNameSecond").show();
                    if (queueStatus == 2) {
                        layer.alert("您所选队列已离线，请为其指定其他队列或继续分诊。", {
                            closeBtn: 0,
                            // btn: ['确定'],
                            icon: 7,
                            zIndex: 19892002,
                            cancel: function () {
                            },
                            yes: function (index) {
                                var msg = "该患者初诊医生已不在线！";
                                doctorNameInfo(queueId, relationType, msg,deptid);
                                layer.close(layer.index);
                            }
                        })
                    } else {
                        var msg = "该患者初诊医生已不在线！";
                        doctorNameInfo(queueId, relationType, msg,deptid);
                    }
                }
            }
        }
    });
}

//手动分诊
function manualTriage(signData, queueId) {
    var queueKey = '';
    var signId = signData.signId;
    var signTime = signData.signTime;
    var doctorId = $('#txt_doctorNames option:selected').val() ||'';
    var doctorName = $('#txt_doctorNames option:selected').text() ||'';
    //var doctorName = $("#hid_doctorName").val();
    //var doctorId = $("#hid_doctor").val();
    for (var i = 0; i < qListJsonStr.length; i++) {
        if (queueId == qListJsonStr[i].queueId) {
            queueKey = qListJsonStr[i].queueKey;
        }
    }
    /*var doctorNameType = $('#txt_doctorNames option:selected').text();*/
    if (doctorName == "全部医生") {
        doctorName = "";
        doctorId = "";
    }
    $.ajax({
        url: manualTriageUrl,
        type: 'post',
        data: {
            hospitalId: _hospiId,
            editor: userId,
            signIds: signId,
            queueKey: queueKey,
            pretestStage: btnType,
            doctorId: doctorId,
            doctorName: doctorName
        },
        beforeSend: function () {
            // 禁用按钮防止重复提交
            $("#confirmArrival").attr({ disabled: "disabled" });
        },
        complete: function () {
            // 禁用按钮防止重复提交
            $("#confirmArrival").removeAttr("disabled");
        },
        success: function (d) {

            var jsonObj = JSON.parse(d);
            if (jsonObj.status == '0') {
                // layer.alert(jsonObj.desc, {icon: 1});
                if (jsonObj.data != null && jsonObj.data != '' && jsonObj.data.length > 0) {
                    $("#hid_registerId").val(jsonObj.data[0].registerId);//就诊序号
                    $("#hid_prePatientNum").val(jsonObj.data[0].prePatientNum);//排队人数

                    try {
                        // 打印报到凭证
                        //registerPrintByCSharp(signTime);
                        var sign = $('#hid_isSign').val();
                        var id =  signId;
                        if(sign==0){
                            id =  $('#hid_id').val();
                        }
                        getTicketInfo(id);
                    } catch (error) {
                        layer.alert('未检测到打印机驱动：' + error, { icon: 2 });
                    }
                }
                layer.closeAll();
                parent.layer.closeAll();
                // 未报到列表无须打开
                if(!_from || _from!='wbd'){
                    //报到成功之后再次报到弹窗
                    parent.document.getElementById('d_right_content').getElementsByTagName('iframe')[0].contentWindow.autoXcbd();
                }

            } else {
                layer.closeAll();
                layer.alert(jsonObj.desc, { icon: 2 });
            }
        }
    });
}
// 获取当前时间，并按yyyy-MM-dd hh:mm:ss 格式输出
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var strHours = date.getHours();
    var strMinutes = date.getMinutes();
    var strSeconds = date.getSeconds();
    var currentdate = date.getFullYear() + seperator1 + toDou(month) + seperator1 + toDou(strDate)
        + " " + toDou(strHours) + seperator2 + toDou(strMinutes) + seperator2 + toDou(strSeconds);
    return currentdate;
}

//时间补 0
function toDou(num) {
    var num = num + "";
    return num = num.length > 1 ? num : 0 + num;
}
function getTicketInfo(id) {
    $.ajax({
        url: ajaxPrintTicket+'?id='+id+'&machineId=',
        type: 'post',
        success: function (d) {
           var res = JSON.parse(d);
           if(res.status==0){
               dealTicket(res.data)
           }
        },
        error: function () {

        }
    });
}
function dealTicket(res) {
    var arr = res.content ||[];
    var fontArr = [18,24,36];// 字体大小  对应安卓的 小 中 大
    // 将这部分分开，原因是返回的是数组，顺序不确定
    var title = ''; // 标题
    var frag = '<div>'; // 主体部分
    var tips = ''; // 温馨提示
    var imgCode = '';// 二维码
    var obj = {};
    var rowspacing = res.rowspacing;
    var patientId = '';
    for(var i=0;i<arr.length;i++){
        if(arr[i]['isUsed']=='true'){
            obj[arr[i]['eKey']] = {
                title:arr[i]['cKey'],
                editAttr:JSON.parse(arr[i]['editAttr']),
                value2:arr[i]['value2']||'',
                value:arr[i]['value']
            }
        }
    }
    for (var k in obj){
        var fonts = parseInt(obj[k].editAttr.font);
        var isweight = obj[k].editAttr.isweight;
        // 标题
        if(k=='title'){
            title += '<div style="font:'+(fontArr[fonts]||18)+'px/'+(fontArr[fonts]||18)+'px SimSun;text-align:center;margin:0 0 24px;font-weight:'+(isweight==1?'900':'normal')+'">'+obj[k].value+'</div>';
        // 温馨提示
        }else if(k=='reminder'){
            tips = dealTips(obj[k]['value2'],obj[k]['editAttr']);
        // 二维码
        }else if(k=='qRcode'){
            imgCode +='<div id="imgCode" class="imgCode" style=";margin:0 0 24px;"></div>';
            patientId =obj[k]['value'];
        }else {
            frag +='<p style="font: '+(fontArr[fonts]||18)+'px/'+(fontArr[fonts]||18)+'px SimSun;font-weight:'+(isweight==1?'900':'normal')+';margin:0 0 '+rowspacing+'px;">'+obj[k].title+':'+(obj[k].value||'')+'</p>';
        }
    }
    frag +='</div>';
    $('#print').html(title+imgCode+frag+tips);
    if(patientId!=''){
        $("#imgCode").qrcode({
            width: 90, //宽度
            height: 90, //高度
            text: patientId
        });
        var canvas = $("#imgCode canvas");
        //将canvas转换成png图片，才能被打印机识别打印
        var img = canvas[0].toDataURL("image/png");
        $("#imgCode").html("<img style='width: 90px;height: 90px;display: block;margin: 0 auto' src='" + img + "'>");
    }
    var printData = document.all.item("print").innerHTML;
    var htmlText = "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta charset=\"utf-8\" /><title></title></head><body>" +
        "<div id=\"print\" style=\"width: 70mm; height:135mm;left:15px;position:absolute\">" + printData + "</div></body></html>";

    try{
        // 通知csharp做打印
        PrintByCSharp(patientId, htmlText);
    }catch (e) {
        console.warn(e.message)
    }
}
function dealTips(str,attr) {
    var fontArr = [18,24,36];// 字体大小  对应安卓的 小 中 大
    var fonts = parseInt(attr.font);
    return '<div style="font: '+(fontArr[fonts]||18)+'px/'+(fontArr[fonts]||18)+'px SimSun;font-weight:'+(attr.isweight==1?'900':'normal')+';">'+str+'</div>';

}
function batchCheck() {
     parent&&parent.layer.closeAll();
     parent.$('#d_right_content iframe')[0].contentWindow.batchChecks();
}

